﻿using System;
using System.Collections.Generic;
using System.Data;
using UFIDA.U8.MomServiceCommon;
using U8Login;
using CoreSoft.Frame.Entity;
using CoreSoft.Frame.Entity.http;
using U8API.Pub;

namespace U8API.Plugin
{
    public class CustomerPlugin
    {
        //private readonly string _ip = ConfigurationManager.AppSettings["WmsIP"] + "Customerapi";
        //private readonly string _ip = "http://10.10.73.26:8888/api/" + "Customerapi";
        public static string constr = "";
        private string url = "";

        private String GetCustJs(clsLogin login, MSXML2.IXMLDOMDocument2 domhead, int operation)
        {

            var datatable = Common.GetUrl(constr, login.get_cAcc_Id()).Tables[0];
            var datarow = datatable.Rows[0];
            url = datarow[1] + "receiveCustomer";
            //var datatabledept = Common.GetUser(constr).Tables[0];
            //DebugWriteLog.WriteLine("cAcc_Id:" + login.get_cAcc_Id() + ",count:" + datatabledept.Rows.Count);
            //bool hasdept = false;
            //foreach (DataRow item in datatabledept.Rows)
            //{
            //    //部门code
            //    var deptcode = item[1].ToString();
            //    //过滤如果不是QZ不触发插件
            //    if (deptcode == login.get_cAcc_Id())
            //    {
            //        DebugWriteLog.WriteLine("cAcc_Id:" + login.get_cAcc_Id() + ",deptcode:" + deptcode);
            //        hasdept = true;
            //    }
            //}
            //if (!hasdept)//限制
            //{
            //    return "Nopermission";
            //}
            //MSXML2.IXMLDOMNode tmpNode = domhead.selectSingleNode("/customer");
            //String custcode = tmpNode.attributes.getNamedItem("ccuscode").nodeValue.ObjToString();
            //String custname = tmpNode.attributes.getNamedItem("ccusname").nodeValue.ObjToString();
            //string ccode = tmpNode.attributes.getNamedItem("ccccode").nodeValue.ObjToString();

            String custcode = domhead.selectSingleNode("//ccuscode").nodeTypedValue.ObjToString();//客户编号-plf(修改)
            
            DebugWriteLog.WriteLine("custcode:" + custcode);
            List<Customer> custdatas = new List<Customer>();
            if (operation != 1) //不是删除
            {
                String custname = domhead.selectSingleNode("//ccusname").nodeTypedValue.ObjToString();
                String ccusabbname = domhead.selectSingleNode("//ccusabbname").nodeTypedValue.ObjToString();
                //客户简称-plf-2017-11-10
                string ccode = domhead.selectSingleNode("//ccccode").nodeTypedValue.ObjToString();

                var reserved5 = domhead.selectSingleNode("//ccusdefine12").nodeTypedValue.ObjToFloat();
                    //产品保质期-plf-2017-12-01
                //产品保质期-plf-2017-12-01

                Int32 StartFlag = 1;

                Customer data = new Customer();
                data.CustomerCCode = ccode;
                data.CustomerName = custname;
                data.ShortName = ccusabbname;
                data.StartFlag = StartFlag;
                data.CustomerCode = custcode;

                data.Reserved5 = reserved5;
                custdatas.Add(data);
            }
            else
            {
                custdatas.Add(new Customer{CustomerCode = custcode});
            }
            ApiRequest req = new ApiRequest();
            req.data = custdatas;//.ToJson();
            req.orgcode = login.get_cAcc_Id();
            req.primarykey = custcode;
            req.operation = operation;
            DebugWriteLog.WriteLine("客户档案", "GetCustJs", req.ToJson());
            return req.ToJson();
        }
        public bool Update_After(ref MSXML2.IXMLDOMDocument2 domhead, ref string errMsg)
        {
            //获取插件上下文
            bool bresult = true;
            MomCallContext ctx = MomCallContextCache.Instance.CurrentMomCallContext;

            //从上下文获取U8Login对象
            U8Login.clsLogin login = ctx.U8Login as U8Login.clsLogin;
            if (login != null)
                constr = login.UFDataConnstringForNet;
            String js = "";
            try
            {
                js = GetCustJs(login, domhead, 2);
                //不是qz直接返回true
                if (js == "Nopermission")
                {
                    return true;
                }
                //var rr = PostHttpHelper.GetHttp(url, "", "application/json; charset=utf-8", 1000);
                var result = HttpHelper.PostDataToServer(url, js);
                var apiresult = Common.DeserializeObject<ApiResponse>(result);
                if (apiresult.successful != 0)
                {
                    errMsg = apiresult.message;
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                bresult = false;
                errMsg = "接口错误" + url + js + ex.Message;
            }
            return bresult;
        }


        public bool Update_After_plm(ref MSXML2.IXMLDOMDocument2 domhead, ref string errMsg)
        {
            //获取插件上下文
            bool bresult = true;
            MomCallContext ctx = MomCallContextCache.Instance.CurrentMomCallContext;

            //从上下文获取U8Login对象
            U8Login.clsLogin login = ctx.U8Login as U8Login.clsLogin;
            if (login != null)
                constr = login.UFDataConnstringForNet;
            Dictionary<string, string> js;
            try
            {
                js = GetCustJsPlm(login, domhead, 0);
                //不是qz直接返回true
                if (js == null)
                {
                    return true;
                }

                var result = HttpHelper.PostDataToServerDic(url, js, "application/x-www-form-urlencoded");
                var apiresult = Common.DeserializeObject<ApiResponse>(result);
                if (apiresult.successful != 0)
                {
                    errMsg = apiresult.message;
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                bresult = false;
                errMsg = "接口错误"  + ex.Message;
                DebugWriteLog.WriteLine("InventoryPlugin", "异常", ex );
            }
            return bresult;
        }

        private Dictionary<string, string> GetCustJsPlm(clsLogin loginObj, MSXML2.IXMLDOMDocument2 domhead, int operation)
        {
            try
            {
                var datatable = Common.GetPlmUrl(constr, loginObj.get_cAcc_Id()).Tables[0];
                var datarow = datatable.Rows[0];
                url = datarow[1].ObjToString() + "IF_04?";

                string ccuscode = domhead.selectSingleNode("//ccuscode") == null ? "" : domhead.selectSingleNode("//ccuscode").nodeTypedValue.ObjToStringNull();//客户编码
                string ccusname = domhead.selectSingleNode("//ccusname") == null ? "" : domhead.selectSingleNode("//ccusname").nodeTypedValue.ObjToStringNull();//客户全称 
                string ccusabbname = domhead.selectSingleNode("//ccusabbname") == null ? "" : domhead.selectSingleNode("//ccusabbname").nodeTypedValue.ObjToStringNull();//客户简称
                string customerkcode = domhead.selectSingleNode("//customerkcode ") == null ? "" : domhead.selectSingleNode("//customerkcode ").nodeTypedValue.ObjToStringNull();//客户等级
                string ccusdefine1 = domhead.selectSingleNode("//ccusdefine1") == null ? "" : domhead.selectSingleNode("//ccusdefine1").nodeTypedValue.ObjToStringNull();//临时编码
                Dictionary<string, string> dic = new Dictionary<string, string>();
                dic.Add("fth4khbm", ccuscode);
                dic.Add("fth4khmc", ccusname);
                dic.Add("fth4khjc", ccusabbname);
                dic.Add("fth4khdj", customerkcode);
                dic.Add("itemid", ccusdefine1);
                dic.Add("orgcode", loginObj.get_cAcc_Id());


                DebugWriteLog.WriteLine("InventoryPlugin", "GetCustJsPlm抛出参数", "ccuscode = " + ccuscode + "ccusname = " + ccusname + " customerkcode = " + customerkcode + " ccusdefine1 = " + ccusdefine1);
                return dic;
            }
            catch (Exception e)
            {
                DebugWriteLog.WriteLine("InventoryPlugin", "异常", e);
                throw e;
            }
        }
        public bool Insert_After(ref MSXML2.IXMLDOMDocument2 domhead, ref string errMsg)
        {
            //获取插件上下文
            bool bresult = true;
            MomCallContext ctx = MomCallContextCache.Instance.CurrentMomCallContext;

            //从上下文获取U8Login对象
            U8Login.clsLogin login = ctx.U8Login as U8Login.clsLogin;
            if (login != null)
                constr = login.UFDataConnstringForNet;
            String js = "";
            try
            {
                js = GetCustJs(login, domhead, 0);
                //不是qz直接返回true
                if (js == "Nopermission")
                {
                    return true;
                }
                var result = HttpHelper.PostDataToServer(url, js);
                var apiresult = Common.DeserializeObject<ApiResponse>(result);
                if (apiresult.successful != 0)
                {
                    errMsg = apiresult.message;
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                bresult = false;
                errMsg = "接口错误" + url + js + ex.Message;
            }
            return bresult;
        }
        public bool Delete_After(ref MSXML2.IXMLDOMDocument2 domhead, ref string errMsg)
        {
            //获取插件上下文
            bool bresult = true;
            MomCallContext ctx = MomCallContextCache.Instance.CurrentMomCallContext;

            //从上下文获取U8Login对象
            U8Login.clsLogin login = ctx.U8Login as U8Login.clsLogin;
            if (login != null)
                constr = login.UFDataConnstringForNet;
            String js = "";
            try
            {
                js = GetCustJs(login, domhead, 1);
                //不是qz直接返回true
                //if (js == "Nopermission")
                //{
                //    return true;
                //}
                var result = HttpHelper.PostDataToServer(url, js);
                var apiresult = Common.DeserializeObject<ApiResponse>(result);
                if (apiresult.successful != 0)
                {
                    errMsg = apiresult.message;
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                bresult = false;
                errMsg = "接口错误" + url + js + ex.Message;
            }
            return bresult;
        }
    }
}
